Leetcode-Merge Two Sorted Lists

Merge Two Sorted Lists

合并两个有序链表。
Description

解题思路
此题比较简单,采用迭代的方式。由于链表已经是有序的,所以依次比较两个链表当前元素的大小,然后将较小的元素加入到新的链表中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = cur = ListNode(1) # 第一个节点可以任取
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return result.next